package com.yc.cloud.admin.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yc.cloud.admin.service.SnapshotStorageService;
import com.yc.cloud.common.oss.service.OssFileService;
import com.yc.cloud.entity.HwCameraSnapshotRecord;
import com.yc.cloud.mapper.HwCameraSnapshotRecordMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 抓图存储服务实现
 * 
 * @author kinggu
 * @since 2025-10-10
 */
@Slf4j
@Service
public class SnapshotStorageServiceImpl implements SnapshotStorageService {
    
    @Resource
    private HwCameraSnapshotRecordMapper snapshotRecordMapper;
    
    @Resource
    private OssFileService ossFileService;
    
    @Value("${snapshot.storage.base-path:/data/snapshots}")
    private String basePath;
    
    @Value("${snapshot.storage.base-url:http://localhost:8080}")
    private String baseUrl;
    
    @Override
    public String saveSnapshotImage(Long cameraId, String imageBase64, String imageFormat) {
        try {
            // 1. 解码base64
            byte[] imageBytes = Base64.decode(imageBase64);
            
            // 2. 生成文件路径: /basePath/camera_id/yyyy-MM-dd/HHmmss_timestamp.jpg
            LocalDateTime now = LocalDateTime.now();
            String datePath = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String fileName = now.format(DateTimeFormatter.ofPattern("HHmmss")) 
                + "_" + System.currentTimeMillis() 
                + "." + imageFormat;
            
            String relativePath = String.format("camera_%d/%s/%s", cameraId, datePath, fileName);
            String fullPath = basePath + File.separator + relativePath;
            
            // 3. 确保目录存在
            FileUtil.mkParentDirs(fullPath);
            
            // 4. 保存文件
            FileUtil.writeBytes(imageBytes, fullPath);
            
            log.info("保存抓图文件成功: {}, 大小: {} bytes", relativePath, imageBytes.length);
            
            return relativePath;
            
        } catch (Exception e) {
            log.error("保存抓图文件失败", e);
            return null;
        }
    }
    
    @Override
    public String generateThumbnail(String originalPath, int width, int height) {
        // TODO: 实现缩略图生成逻辑
        // 可以使用 thumbnailator 或 ImageUtils 来生成缩略图
        log.debug("生成缩略图: {}, 尺寸: {}x{}", originalPath, width, height);
        
        // 暂时返回缩略图路径（实际需要生成）
        String thumbnailPath = originalPath.replace("camera_", "thumbnail_camera_");
        return thumbnailPath;
    }
    
    @Override
    public String getSnapshotUrl(String filePath) {
        if (filePath == null) {
            return null;
        }
        return baseUrl + "/api/snapshots/images/" + filePath;
    }
    
    @Override
    public int deleteAllSnapshots(Long cameraId) {
        log.info("删除摄像头[{}]的所有抓图", cameraId);
        
        int deletedCount = 0;
        
        try {
            List<HwCameraSnapshotRecord> records = snapshotRecordMapper.selectList(
                new QueryWrapper<HwCameraSnapshotRecord>()
                    .eq(HwCameraSnapshotRecord.CameraId, cameraId)
                    .eq(HwCameraSnapshotRecord.Deleted, false)
            );
            
            for (HwCameraSnapshotRecord record : records) {
                // 删除 OSS 上的原图
                if (record.getFileId() != null) {
                    ossFileService.deleteByFileId(record.getFileId());
                }
                
                // 删除 OSS 上的缩略图
                if (record.getThumbnailFileId() != null) {
                    ossFileService.deleteByFileId(record.getThumbnailFileId());
                }
                
                // 标记数据库记录为已删除
                record.setDeleted(true);
                snapshotRecordMapper.updateById(record);
                deletedCount++;
            }
            
            log.info("删除摄像头[{}]的抓图完成，删除数量: {}", cameraId, deletedCount);
            
        } catch (Exception e) {
            log.error("删除摄像头抓图失败", e);
        }
        
        return deletedCount;
    }
    
    @Override
    public boolean deleteSnapshotFile(String fileId) {
        try {
            if (fileId == null || fileId.isEmpty()) {
                log.warn("文件ID为空，跳过删除");
                return true;
            }
            
            boolean deleted = ossFileService.deleteByFileId(fileId);
            if (deleted) {
                log.debug("删除OSS文件成功: {}", fileId);
            } else {
                log.warn("删除OSS文件失败: {}", fileId);
            }
            return deleted;
        } catch (Exception e) {
            log.error("删除OSS文件异常: {}", fileId, e);
            return false;
        }
    }
}

